package basicCompiler;

import java.util.Scanner;
import java.util.Stack;

import basicCompiler.visitor.AbstractTreeVisitor;
import basicCompiler.visitor.TreeVisitor;

public class Parser {
	Stack<Node> results;
	Stack<AbstractOperator> operators;
	
	String text;
	
	public Parser( String s){
		this.text = s;
		results = new Stack<Node>();
		operators = new Stack<AbstractOperator> ();
	}
	
	public Node Parse(){
		
		Scanner sc = new Scanner( text);
		while (sc.hasNext()) {
			String exp = sc.next();
			// Create nodes
			Node node = NodeFactory.createNode(exp);
			// Add nodes to stack 
			AbstractTreeVisitor v = new TreeVisitor();
			node.accept( v, results, operators);			
		}
		
		// Empty operators stack
		while ( ! operators.isEmpty()){
			Node o = operators.pop();
			Node right = results.pop();
			Node left = results.pop();
			o.setChildren(left, right);
			results.push(o);
		}
		return results.pop();
	}
}
